from django.utils.decorators import method_decorator

from gis.common import track_logging
from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView
from gis.common.exceptions import BizException, BizErrorCode
from itpay.core.agency import agency_service
from itpay.core.agency.const import AgencyType
from itpay.core.agency.errors import ERROR_AGREE_AGENCY_NOT_BELONG
from itpay.core.conf import IMConf
from itpay.core.mch import service
from itpay.server_agency.decorators import require_login
from itpay.server_agency.view.agency import helper
from itpay.server_agency.view.im.forms import (
    ListTopicSchema,
    TopicMessagesSchema,
    MessagesSchema,
    SendMessageSchema,
)
from itpay.utils import rpc

_LOGGER = track_logging.getLogger(__name__)


class ListTopicView(BaseView):
    @method_decorator(require_login())
    @method_decorator(validate_parameters(ListTopicSchema))
    def get(self, request, cleaned_data):

        cleaned_data["app_id"] = IMConf.app_id
        user = request.user
        parent_id = agency_name = None
        if user["agency_type"] == AgencyType.ADMIN_AGENCY.value:
            parent_id = user["id"]
            agency_name = cleaned_data.get("agency_name")
            if agency_name is not None:
                del cleaned_data["agency_name"]

            agency_id = cleaned_data.get("agency_id")
            if agency_id is not None:
                del cleaned_data["agency_id"]
        else:
            agency_id = request.user_id

        if agency_name or parent_id or agency_id:
            _, agencies = agency_service.list_agency(
                1, 100, id=agency_id, agency_name=agency_name, parent_id=parent_id
            )

            if not agencies:
                return {"total": 0, "list": []}
            agency_ids = ",".join([str(e["id"]) for e in agencies])
            cleaned_data["agency_ids"] = agency_ids

        cleaned_data["is_replied"] = (
            -1
            if cleaned_data.get("is_replied") is None
            else 1
            if cleaned_data["is_replied"]
            else 0
        )

        response = rpc.do_get(
            IMConf.host + "open/pay/messages/topics/", cleaned_data, IMConf.api_key
        )
        if response.get("data") and response.get("data").get("list"):
            lll = []
            for e in response["data"]["list"]:
                try:
                    mch = service.get_mch(e["player_mch_id"])
                    e["player_mch"] = dict(id=mch["id"], name=mch["name"])
                    del e["player_mch_id"]
                    lll.append(helper.wrapper_agency_name(e))
                except Exception:
                    _LOGGER.info("wrap agency fail", exc_info=True)
            response["data"]["list"] = lll
        else:
            return {"total": 0, "list": []}
        return response["data"]


class ListTopicMessagesView(BaseView):
    @method_decorator(require_login())
    @method_decorator(validate_parameters(TopicMessagesSchema))
    def get(self, request, topic_id, cleaned_data):
        cleaned_data["app_id"] = IMConf.app_id

        response = rpc.do_get(
            IMConf.host + "open/pay/messages/topics/{}/".format(topic_id),
            cleaned_data,
            IMConf.api_key,
        )
        if "agency" not in response["data"]:
            raise Exception("Error IM Server")

        del response["data"]["agency"]["platform"]

        mch = service.get_mch(response["data"]["player"]["platform"]["id"])
        response["data"]["player"]["mch"] = dict(id=mch["id"], name=mch["name"])
        del response["data"]["player"]["platform"]

        return response["data"]


class ListMessagesView(BaseView):
    @method_decorator(require_login())
    @method_decorator(validate_parameters(MessagesSchema))
    def get(self, request, cleaned_data):
        user_id = request.user_id
        if not agency_service.check_agency_parent(cleaned_data["agency_id"], user_id):
            raise BizException(ERROR_AGREE_AGENCY_NOT_BELONG)
        cleaned_data["app_id"] = IMConf.app_id
        response = rpc.do_get(
            IMConf.host + "open/pay/messages/", cleaned_data, IMConf.api_key
        )
        if "agency" not in response["data"]:
            raise Exception("Error IM Server")

        del response["data"]["agency"]["platform"]

        mch = service.get_mch(response["data"]["player"]["platform"]["id"])
        response["data"]["player"]["mch"] = dict(id=mch["id"], name=mch["name"])
        del response["data"]["player"]["platform"]

        return response["data"]

    @method_decorator(require_login())
    @method_decorator(validate_parameters(SendMessageSchema))
    def post(self, request, cleaned_data):
        user = request.user
        if user["agency_type"] == AgencyType.ADMIN_AGENCY.value:
            raise BizException(BizErrorCode(1, "总代账户不能给玩家发送消息"))
        params = {
            "app_id": IMConf.app_id,
            "play_mch_id": cleaned_data["play_mch_id"],
            "player_id": cleaned_data["player_id"],
            "agency_id": request.user_id,
            "message": cleaned_data["message"],
        }
        _LOGGER.info("send message to play params {}".format(params))
        rpc.do_post(
            IMConf.host + "open/pay/send_message_to_play/", params, IMConf.api_key
        )
